<?php

namespace App\V3\V3_1\Controllers;

use App\V3\V3_1\Models\CalcExpressMasterModel;
use App\V3\V3_1\Models\ExpressTempleteModel;
use App\V3\V3_1\Services\ExpressTempleteService;
use App\Rules\JsonArray;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

class ExpressTempleteController extends BaseController
{
    /**
     * 新建快递模板
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/5/28 11:13
     * @return \Illuminate\Http\JsonResponse
     */
    public function add(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
//            'kuaidi_id' => 'required|numeric|min:0',
            'kuaidi_name' => 'required'
        ],[
//            'kuaidi_id.required' => '请选择快递公司',
//            'kuaidi_id.numeric' => '快递id只能为数字',
//            'kuaidi_id.min' => '快递id异常',
            'kuaidi_name.required' => '快递名称缺失',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        $data['kuaidi_id'] = 0;
        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();

        $this->log('创建快递模板', $data);
        return response()->json(
            ExpressTempleteService::add($data)
        );
    }

    /**
     * 编辑快递模板
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/5/30 9:58
     * @return \Illuminate\Http\JsonResponse
     */
    public function edit(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required',
//            'kuaidi_id' => 'required|numeric|min:0',
            'kuaidi_name' => 'required'
        ],[
            'id.required' => '参数id缺失',
//            'kuaidi_id.required' => '请选择快递公司',
//            'kuaidi_id.numeric' => '快递id只能为数字',
//            'kuaidi_id.min' => '快递id异常',
            'kuaidi_name.required' => '快递名称缺失',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        $data['kuaidi_id'] = 0;

        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();

        $this->log('编辑快递模板', $data);
        return response()->json(
            ExpressTempleteService::edit($data)
        );
    }

    /**
     * 删除快递模板
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/5/30 16:56
     * @return \Illuminate\Http\JsonResponse
     */
    public function del(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required',
        ],[
            'id.required' => '参数id缺失',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        ExpressTempleteModel::where('id', $data['id'])->update(['is_del' => 1]);

        $this->log('删除快递模板', $data);
        return $this->success();
    }

    /**
     * 快递模板详情
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/5/31 14:04
     * @return \Illuminate\Http\JsonResponse
     */
    public function detail(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required',
        ],[
            'id.required' => '参数id缺失',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        return $this->success(
            ExpressTempleteService::detail($data['id'])
        );
    }

    /**
     * 快递模板列表
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/5/30 16:59
     * @return \Illuminate\Http\JsonResponse
     */
    public function list(Request $request)
    {
//        if($this->getMainUserId() == $this->getUserId()) {
//            $userId['main_id'] = ['EQ' => $this->getMainUserId()];
//        }
//        else {
//            $userId['user_id'] = ['EQ' => $this->getUserId()];
//        }

        $userId['main_id'] = ['EQ' => $this->getMainUserId()];

        $isPage = isset($request->is_page)?$request->is_page:0;

        if(isset($request->is_page)) {
            if(!in_array($isPage,[0,1])) {
                return $this->fail('', '参数`is_page`不合法，请重试');
            }
        }

        $data = [];
        if($isPage) {
            //参数验证
            $validator = Validator::make($data = $request->all(), [
                'pageSize' =>'required|integer|min:1',//页面大小
                'currentPage' =>'required|integer',//当前页
            ],[
                'pageSize.required' => '`页面大小`缺失',
                'pageSize.integer' => '`页面大小`只能为数字',
                'pageSize.min' => '`页面大小`默认最小仅能为1',
                'currentPage.required' => '`页面大小`缺失',
                'currentPage.integer' => '`页面大小`只能为数字',
                'currentPage.min' => '`页面大小`默认最小仅能为1',
            ]);

            //参数错误响应
            if ($info = $validator->errors()->first()) {
                return $this->fail('', $info);
            }
        }

        return $this->success(ExpressTempleteService::list($userId, $isPage, $data));
    }

    public function top(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required',
        ],[
            'id.required' => '参数id缺失',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        $this->log('置顶快递模板', $data);
        return response()->json(
            ExpressTempleteService::top($data)
        );
    }

    /**
     * 取消置顶快递模板
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/5/31 14:57
     * @return \Illuminate\Http\JsonResponse
     */
    public function cancelTop(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required',
        ],[
            'id.required' => '参数id缺失',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        $this->log('取消置顶快递模板', $data);
        return response()->json(
            ExpressTempleteService::cancelTop($data)
        );
    }

    //目的地省份城市列表
    public function termini()
    {
        if($this->getMainUserId() == $this->getUserId()) {
            $userId['main_id'] = ['EQ' => $this->getMainUserId()];
        }
        else {
            $userId['user_id'] = ['EQ' => $this->getUserId()];
        }

        return $this->success(ExpressTempleteService::termini($userId));
    }

    /**
     * 保存快递计算结果
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/5/30 18:55
     * @return \Illuminate\Http\JsonResponse
     */
    public function addCalc(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'to_province' => 'required_without:to_city',
//            'spec_info' => 'required',
            'calc_title' => 'required',
            'calc_type' =>[
                'required',
                Rule::In([0,1]),
            ],//快递类型;0:一单一件;1:一单多件;
            'spec_info' => [
                'required',
                'json',
                new JsonArray([
                    'length' => 'numeric|min:0.01',
                    'width' => 'numeric|min:0.01',
                    'height' => 'numeric|min:0.01',
                    'act_weight' => 'numeric|min:0.01',
                    'amount' => 'numeric|min:0.01'
                ])
            ]
        ], [
            'calc_title.required' => '计算结果记录的标题不能为空',
            'to_province.required_without' => '请选择目的地省份或城市',
            'calc_type.required' => '请选择快递类型',
            'calc_type.in' => '快递类型不合法',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();

        $this->log('保存快递计算结果', $data);
        return response()->json(
            ExpressTempleteService::addCalc($data)
        );
    }

    /**
     * 修改快递计算结果
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/5/31 14:40
     * @return \Illuminate\Http\JsonResponse
     */
    public function editCalc(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required',
            'to_province' => 'required_without:to_city',
            'spec_info' => 'required',
            'calc_title' => 'required',
            'calc_type' =>[
                'required',
                Rule::In([0,1]),
            ],//快递类型;0:一单一件;1:一单多件;
        ],[
            'id.required' => '参数id缺失',
            'calc_title.required' => '计算结果记录的标题不能为空',
            'to_province.required_without' => '请选择目的地省份或城市',
            'calc_type.required' => '请选择快递类型',
            'calc_type.in' => '快递类型不合法',
            'spec_info.required' => '请填写规格信息',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        $this->log('修改快递计算结果', $data);

        return response()->json(
            ExpressTempleteService::editCalc($data)
        );
    }

    /**
     * 快递计算结果列表
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/5/31 15:31
     * @return \Illuminate\Http\JsonResponse
     */
    public function listCalc(Request $request)
    {
            if($this->getMainUserId() == $this->getUserId()){
                $userId['main_id'] = ['EQ' => $this->getMainUserId()];
            }else{
                if($this->isShareExpressCalc()){
                $userId['main_id'] = ['EQ' => $this->getMainUserId()];
                }else{
                $userId['user_id'] = ['EQ' => $this->getUserId()];
                }
            }

        return $this->success(
            ExpressTempleteService::listCalc($userId)
        );
    }

    /**
     * 删除快递计算结果
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/5/31 15:33
     * @return \Illuminate\Http\JsonResponse
     */
    public function deCalc(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required',
        ],[
            'id.required' => '参数id缺失',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        $this->log('删除快递计算结果', $data);
        CalcExpressMasterModel::where('id', $data['id'])->update(['is_del' => 1]);
        return $this->success();
    }

    /**
     * 计算快递结果详细
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/5/31 16:38
     * @return \Illuminate\Http\JsonResponse
     */
    public function detailCalc(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required',
        ],[
            'id.required' => '参数id缺失',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        return $this->success(ExpressTempleteService::detailCalc($data['id']));
    }

    /**
     *
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/6/1 10:49
     * @return \Illuminate\Http\JsonResponse
     */
    public function calc(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required_without:spec_info',
            'spec_info' => 'required_without:id',
            'sort' =>[
                Rule::In([0,1]),
            ],
//            'to_city' => 'required_with:to_province',
        ],[
            'id.required_without' => '参数id或者spec_info缺失',
            'spec_info.required_without' => '参数id或者spec_info缺失',
            'sort.in' => '排序方式不合法'
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        $data['kuaidi_id'] = empty($data['kuaidi_id'])?0:$data['kuaidi_id'];

        if($this->getMainUserId() == $this->getUserId() || $this->isShareExpressCalc()) {
            $userId['a.main_id'] = ['EQ' => $this->getMainUserId()];
        }
        else {
            $userId['a.user_id'] = ['EQ' => $this->getUserId()];
        }

        return response()->json(
            ExpressTempleteService::calc($data, $userId)
        );
    }

    public function kuaidiList()
    {
//        if($this->getMainUserId() == $this->getUserId()) {
//            $userId['main_id'] = ['EQ' => $this->getMainUserId()];
//        }
//        else {
//            $userId['user_id'] = ['EQ' => $this->getUserId()];
//        }

        $userId['main_id'] = ['EQ' => $this->getMainUserId()];

        $result = ExpressTempleteModel::select(
            'kuaidi_id',
            'kuaidi_name'
        )->where($userId)->distinct()->get()->toArray();
        return $this->success($result);
    }

    /**
     * 一键清除快递模板
     * AUTHOR  : Sun Wu
     * DateTime: 2022/7/21 15:56
     * @return \Illuminate\Http\JsonResponse
     */
    public function clear()
    {
        if($this->getMainUserId() != $this->getUserId()) {
            return $this->fail('权限不足，请联系主账号');
        }

        ExpressTempleteModel::where('main_id', $this->getMainUserId())
            ->update([
                'is_del' => 1
            ]);

        return $this->success();
    }
}
